﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using KPI.OrganizationDomain.Infrastructure.DbObject;
using KPI.OrganizationDomain.Model.Entity;
using KPI.OrganizationDomain.Model.ValueObject;
using KPI.Utility;

namespace KPI.OrganizationDomain.Infrastructure.DbManager
{
    public class DepartmentManager
    {
        /// <summary>
        /// Creates the department.
        /// </summary>
        /// <param name="department">The department.</param>
        /// <param name="kpiConnection">The kpi connection.</param>
        /// <param name="transaction">The transaction.</param>
        /// <returns></returns>
        public DepartmentTab CreateDepartment(DepartmentTab department, SqlConnection kpiConnection, SqlTransaction transaction)
        {
            SqlCommand command = kpiConnection.CreateCommand();
            if (transaction != null) command.Transaction = transaction;

            command.CommandText = @"insert into Department([Name], [Description], ParentDepartmentID, CreatedDate, LastModifiedDate, Version, IsDeleted) 
values(@name, @description, @parentID, @createdDate, @lastModifiedDate, 0, 0); 
select @newID=SCOPE_IDENTITY()";

            department.LastModifiedDate = DateTime.Now;
            department.Version = 0;
            department.IsDeleted = false;
            
            command.Parameters.Add(new SqlParameter("@name", department.Name));
            command.Parameters.Add(new SqlParameter("@description", department.Description));
            command.Parameters.Add(new SqlParameter("@parentID", department.ParentDepartmentID));
            command.Parameters.Add(new SqlParameter("@createdDate", DateTime.Now));
            command.Parameters.Add(new SqlParameter("@lastModifiedDate", DateTime.Now));

            SqlParameter newID = new SqlParameter("@newId", SqlDbType.Int);
            newID.Direction = ParameterDirection.Output;
            command.Parameters.Add(newID);

            command.ExecuteNonQuery();

            department.DepartmentID = Convert.ToInt32(newID.Value);
            return department;
        }


    }
}
